<template>
  <div class="article-list" ref="articleList" @scroll="scrollEvent">
    <van-pull-refresh v-model="isloading" @refresh="refresh">
      <van-list
        v-if="bol"
        v-model="loading"
        :finished="finished"
        @load="getData"
        finished-text="没有更多了"
      >
        <article-item :item="i" v-for="i in list" :key="i.art_id" />
      </van-list>
    </van-pull-refresh>
  </div>
</template>
<script>
// 导入获取文章列表api
import ArticleItem from './article-item.vue'
import { articles } from '@/api/home.js'
export default {
  name: 'ArticleList',
  components: {
    ArticleItem
  },
  props: ['id'],
  data () {
    return {
      bol: true,
      loading: false,
      finished: false,
      isloading: false,
      timestamp: Date.now(),
      list: [],
      scrollTop: 0
    }
  },
  created () {
    // this.getData()
  },
  methods: {
    // 获取文章列表
    async getData () {
      // 调用接口
      const res = await articles({
        channel_id: this.id,
        timestamp: this.timestamp
      })
      // 将数据push累加
      this.list.push(...res.data.results)
      // 调用接口结束 将loading改为false
      this.loading = false
      // 判断加载是否结束 是否还有下一页
      if (res.data.pre_timestamp) {
        // 有下一页 将时间戳保存
        this.timestamp = res.data.pre_timestamp
      } else {
        // 没有下一页 加载结束 将finished改为true
        this.finished = true
      }
      // console.log(res)
    },
    // 下拉刷新
    refresh () {
      // 将时间戳还原 用于调用首页数据
      this.timestamp = Date.now()
      // 将list数据清空 在调用接口
      this.list = []
      // 还原上拉加载属性
      this.loading = false
      this.finished = false
      // 保证接口调用完成后执行下面代码
      // await this.getData()
      // 调用接口成功 将isloading改为false
      this.isloading = false
      // 静默刷新
      this.bol = false
      this.$nextTick(() => {
        this.bol = true
      })
    },
    scrollEvent () {
      this.scrollTop = this.$refs.articleList.scrollTop
    }
  },
  activated () {
    this.$refs.articleList.scrollTop = this.scrollTop
  },
  deactivated () {}
}
</script>
<style scoped lang="less">
.article-list {
  height: 100%;
  overflow-y: auto;
  padding: 0 16px;
}
</style>
